package com.battle.service.listener;

import com.battle.pojo.dto.userRoleMp.UserAddRoleDto;
import com.battle.pojo.event.department.DeleteDepartmentEvent;
import com.battle.pojo.event.role.DeleteRoleEvent;
import com.battle.pojo.event.tenant.CreateTenantEvent;
import com.battle.pojo.event.tenant.DeleteTenantEvent;
import com.battle.pojo.event.user.DeleteUserEvent;
import com.battle.service.service.in.UserRoleMpService;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * @author Joseph.Li
 * @author joseph.li@king-v.com
 * Created in 2022-06-27 11:47
 */
@Service
public class UserRoleMpListener {

    private final UserRoleMpService userRoleMpService;

    public UserRoleMpListener(UserRoleMpService userRoleMpService) {
        this.userRoleMpService = userRoleMpService;
    }

    /**
     * 串联管理员用户与角色的关联
     * @param event
     */
    @EventListener(CreateTenantEvent.class)
    public void  userRoleMpListenerCreateTenantEvent(CreateTenantEvent event){
        UserAddRoleDto dto=new UserAddRoleDto();
        dto.setUserId(event.getAdminUserId());
        dto.setRoleId(event.getAdminRoleId());
        userRoleMpService.userBindRole(dto);
    }

    /**
     * 监听删除角色事件，删除前校验是否还有用户在使用此角色
     *
     * 清空所有与此角色的关联
     * @param event
     */
    @EventListener(DeleteRoleEvent.class)
    public void  userRoleMpListener(DeleteRoleEvent event){
        Long roleId = event.getRoleId();
        List<Long> roleIdList = Arrays.asList(roleId);
        userRoleMpService.bathRemoveByRoleIdList(roleIdList);
    }


    /**
     * 删除企业事件
     *
     * 清空企业下所有角色的关联
     * @param event
     */
    @EventListener(DeleteTenantEvent.class)
    public void  userRoleMpListener(DeleteTenantEvent event){
        List<Long> roleIdList = event.getRoleIdList();
        userRoleMpService.bathRemoveByRoleIdList(roleIdList);
    }


    /**
     * 监听删除部门事件
     * 结束部门下所有角色与用户的关联
     *
     * @param event
     */
    @EventListener(DeleteDepartmentEvent.class)
    public void  userRoleMpListener(DeleteDepartmentEvent event){
        List<Long> roleIds = event.getRoleIds();
        userRoleMpService.bathRemoveByRoleIdList(roleIds);
    }


    /**
     * 监听删除用户事件
     *
     * 移除用户的所有角色关联
     * @param event
     */
    @EventListener(DeleteUserEvent.class)
    public void  userRoleMpListener(DeleteUserEvent event){
        Long userId = event.getUserId();
        userRoleMpService.removeUserBind(userId);
    }
}
